import React from "react";
import { createForm } from "../../designer-antd-v5/packages/formily-core/src";
import { createSchemaField } from "../../designer-antd-v5/packages/formily-react/src";
import {
  Form,
  FormItem,
  Input,
  Password,
  Submit,
} from "../../designer-antd-v5/packages/formily-antd-v5/src";
import { Tabs, Card, message } from "antd";
import { useNavigate } from "react-router-dom";
import * as ICONS from "@ant-design/icons";

import { VerifyCode } from "./VerifyCode";
import { userLogin } from "../../api/system";
import { LoginReqI } from "../../types/api";
import { setUserAction } from "../../store/actions";
import { store } from "../../store/configureStore";
import styles from "./index.module.less";
import { encryptStr } from "../../lib/utils";

const normalForm = createForm({
  validateFirst: true,
});

const phoneForm = createForm({
  validateFirst: true,
});

const SchemaField = createSchemaField({
  components: {
    FormItem,
    Input,
    Password,
    VerifyCode,
  },
  scope: {
    icon(name: any) {
      return React.createElement(ICONS[name as keyof typeof ICONS]);
    },
  },
});

const normalSchema = {
  type: "object",
  properties: {
    username: {
      type: "string",
      title: "用户名",
      required: true,
      "x-decorator": "FormItem",
      "x-component": "Input",
      "x-component-props": {
        prefix: "{{icon('UserOutlined')}}",
      },
    },
    password: {
      type: "string",
      title: "密码",
      required: true,
      "x-decorator": "FormItem",
      "x-component": "Password",
      "x-component-props": {
        prefix: "{{icon('LockOutlined')}}",
      },
    },
  },
};

const phoneSchema = {
  type: "object",
  properties: {
    phone: {
      type: "string",
      title: "手机号",
      required: true,
      "x-validator": "phone",
      "x-decorator": "FormItem",
      "x-component": "Input",
      "x-component-props": {
        prefix: "{{icon('PhoneOutlined')}}",
      },
    },
    verifyCode: {
      type: "string",
      title: "验证码",
      required: true,
      "x-decorator": "FormItem",
      "x-component": "VerifyCode",
      "x-component-props": {
        prefix: "{{icon('LockOutlined')}}",
      },
      "x-reactions": [
        {
          dependencies: [".phone#value", ".phone#valid"],
          fulfill: {
            state: {
              "component[1].readyPost": "{{$deps[0] && $deps[1]}}",
              "component[1].phoneNumber": "{{$deps[0]}}",
            },
          },
        },
      ],
    },
  },
};

const Login: React.FC = () => {
  const navigate = useNavigate();

  const onFinish = (values: LoginReqI) => {
    // captcha 为一次性使用，验证通过后就作废
    // onCaptchaClick();
    userLogin({
      username: encryptStr(values.username),
      password: encryptStr(values.password),
    })
      .then((res) => {
        console.log(res);
        if (res.data.token) {
          store.dispatch(setUserAction(res.data));
          navigate("/");
        } else {
          navigate("/login");
        }
      })
      .catch((err: any) => {
        console.log(err);
        message.error(err.detail);
        navigate("/login");
      });
  };

  return (
    <div
      className={styles.loginPage}
      style={{
        display: "flex",
        justifyContent: "center",
        background: "#eee",
        padding: "40px 0",
      }}
    >
      <Card style={{ width: 400 }}>
        <Tabs style={{ overflow: "visible", marginTop: -10 }}>
          <Tabs.TabPane key="1" tab="账密登录">
            <Form
              form={normalForm}
              layout="vertical"
              size="large"
              // onAutoSubmit={console.log}
              onAutoSubmit={onFinish}
            >
              <SchemaField schema={normalSchema} />
              <Submit block size="large">
                登录
              </Submit>
            </Form>
          </Tabs.TabPane>
          <Tabs.TabPane key="2" tab="手机登录">
            <Form
              form={phoneForm}
              layout="vertical"
              size="large"
              onAutoSubmit={console.log}
            >
              <SchemaField schema={phoneSchema} />
              <Submit block size="large">
                登录
              </Submit>
            </Form>
          </Tabs.TabPane>
        </Tabs>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
          }}
        >
          <a href="#新用户注册">新用户注册</a>
          <a href="#忘记密码">忘记密码?</a>
        </div>
      </Card>
    </div>
  );
};

export default Login;
